#! /usr/bin/env python
# coding: utf8
# Copyright: Raphael 'kena' Poss <r.c.poss@uva.nl>
# this file is placed in the public domain.
#
# Convert a CSS stylesheet into one for Docutils' LaTeX output.
#
# Usage example::
#
#    pygmentize -S default -f html | pygments_css2sty.py >pygments-default.sty
#
# Versions:
#
# 2012-05-09: Günter Milde <milde@users.sf.net>:
#             Bugfix: do not fail at lines without comment.
#             Support for digits in role names.
#             ``\providecommand`` instead of ``\newcommand``.
#             Renamed from makesty.py to pygments_css2sty.py.
# 2013-03-27: Günter Milde:
#             Implement bugfix from Juan Luis Cano Rodríguez for csnames.

import sys
import re

print '% Stylesheet for syntax highlight with Docutils'
print '% Generated by pygments_css2sty.py from a Pygments CSS style'
print '% (output of `pygmentize -S <style> -f html`).'
print
print r'\RequirePackage{color}'

cnt = 0
for l in sys.stdin:

    if '/*' in l:
        print "% " + l.split('*')[1]
    key = l.split(' ', 1)[0][1:]

    s = '#1'

    if 'color:' in l:
        col = l.split('#',1)[1][:6]
        r = float(int(col[0:2], 16)) / 255.
        g = float(int(col[2:4], 16)) / 255.
        b = float(int(col[4:6], 16)) / 255.
        s = r'\textcolor[rgb]{%.2f,%.2f,%.2f}{%s}' % (r, g, b, s)

    if 'font-style: italic' in l:
        s = r'\textit{%s}' % s
    if 'font-weight: bold' in l:
        s = r'\textbf{%s}' % s

    if 'border:' in l:
        col = l.split('#',1)[1][:6]
        r = float(int(col[0:2], 16)) / 255.
        g = float(int(col[2:4], 16)) / 255.
        b = float(int(col[4:6], 16)) / 255.
        cname = 'DUcolor%d' % cnt
        cnt += 1
        print r'\definecolor{%s}{rgb}{%.2f,%.2f,%.2f}' % (cname, r, g, b)
        s = r'\colorbox{%s}{%s}' % (cname, s)

    if re.match(r'.*[0-9]', key) is None:
        print(r'\providecommand*\DUrole%s[1]{%s}' % (key, s))
    else:
        print(r'\expandafter\providecommand\csname DUrole%s\endcsname[1]{%s}'
              % (key, s))
